package com.sywl.contact.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.sywl.contact.form.FileUploadForm;

@Controller
public class FileUploadController {
	private String saveDirectory = "E://Test//Upload/";
	
	@RequestMapping(value="/show",method=RequestMethod.GET)
	public String displayForm(){
		return "file_upload_form";
	}
	
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public String save(@ModelAttribute("uploadForm")FileUploadForm uploadForm,
			Model map)throws IllegalStateException, IOException{
		List<MultipartFile> files=uploadForm.getFiles();
		List<String> fileNames=new ArrayList<String>();
		if(null!=files&&files.size()>0){
			for(MultipartFile multipartFile:files){
				String fileName=multipartFile.getOriginalFilename();
				//Handle file content- multipartFile.getInputStream()
				if(!"".equalsIgnoreCase(fileName)){
					multipartFile.transferTo(new File(saveDirectory+multipartFile.getOriginalFilename()));
					fileNames.add(fileName);
				}
			}
		}
		map.addAttribute("files",fileNames);
		return "file_upload_success";
	}
}
